<template>
  <d2-container>
    <template slot="header">
      <el-form ref="indexForm" class="header-area" :model="indexForm" label-width="100px" style="height: auto">
        <template>
          <el-row>
            <el-col :span="10">
               <el-form-item label="渠道名称" prop="channelName">
                  <el-input type="text" v-model="indexForm.channelName" placeholder="请输入渠道名称"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="10">
               <el-form-item label="渠道编号" prop="channelCode">
                  <el-input type="text" v-model="indexForm.channelCode" placeholder="请输入渠道编号"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="4">
               <div class="search-submit">
                  <el-button type="primary" @click="submitForm('indexForm')">查询</el-button>
                  <el-button plain @click="resetForm('indexForm')">重置</el-button>
				</div>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </template>

    <template>
		<div class="table-header">
			<el-button type="primary" @click="add">新 增</el-button>
			<el-button type="danger" @click="deleteBatchRows">批量删除</el-button>
		</div>

      <el-table
	    stripe
		border
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            fixed
            prop="channelName"
            label="渠道名称"
            width="110">
          </el-table-column>
          <el-table-column
            fixed
            prop="channelCode"
            label="渠道编号"
            width="110">
          </el-table-column>
          <el-table-column
            fixed
            prop="channelAddress"
            label="渠道详细地址"
            width="110">
          </el-table-column>
          <el-table-column
            fixed
            prop="zipCode"
            label="邮政编码"
            width="110">
          </el-table-column>
          <el-table-column
            fixed
            prop="personInCharge"
            label="负责人"
            width="110">
          </el-table-column>
          <!-- <el-table-column
            fixed
            prop="idNo"
            label="身份证号"
            width="160">
          </el-table-column>
          <el-table-column
            fixed
            prop="bankName"
            label="开户银行"
            width="110">
          </el-table-column>
          <el-table-column
            fixed
            prop="bankNo"
            label="银行卡号"
            width="130">
          </el-table-column> -->
          <el-table-column
            fixed
            prop="phone"
            label="手机号码"
            width="110">
          </el-table-column>
          <el-table-column
            fixed
            align="center"
            prop="status"
            label="状态"
            width="110">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status==0" style="color:#909399;background-color: white;">暂停合作</el-tag>
              <el-tag v-if="scope.row.status==1">正常合作</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            align="center"
            prop="channelType"
            label="渠道类型"
            width="110">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.channelType==0">自营渠道</el-tag>
              <el-tag v-if="scope.row.channelType==1">第三方渠道</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            align="center"
            prop="cooperationPriceRate"
            label="合作价比例"
            width="150" :formatter="forCooperationPriceRate">
          </el-table-column>
          <el-table-column
            fixed
            align="center"
            prop="collectionPeriod"
            label="增加结算周期（天）"
            width="110">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间" :formatter="forDateCreate">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status==0" type="success" size="small" @click="restartCooperation(scope.$index, scope.row)">重启</el-button>
              <el-button v-if="scope.row.status==1" type="info" size="small" @click="suspendCooperation(scope.$index, scope.row)">暂停</el-button>
              <el-button type="warning" size="small" @click="updateRow(scope.row.id)">编辑</el-button>
              <el-button
                @click.native.prevent="deleteRow(scope.$index, scope.row)"
                type="danger"
                size="small">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
    </template>

    <template slot="footer">
      <div class="page">
        <el-pagination
		background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </template>

    <template>
      <div>
          <keep-alive>
              <addPage :addPage="addComponent" @on-addPage-change="onAddPageChange" @on-loadlist-change="fetchData" ></addPage>
          </keep-alive>
      </div>
      <div>
          <keep-alive>
              <updatePage :updatePage="updateComponent" @on-updatePage-change="onUpdatePageChange" @on-loadlist-change="fetchData" :uId="updateId" @on-id-change="onIdChange"></updatePage>
          </keep-alive>
      </div>
    </template>
  </d2-container>
</template>
<script>
import { findAllListByPage, del, operateStatus, restartCooperation, suspendCooperation, deleteBatchChannelInfo } from '@api/channel/channel'
import addPage from './add'
import updatePage from './update'
import dayjs from 'dayjs'
export default {
  name: 'channel-index',
  components: {
    addPage,
    updatePage
  },
  data () {
    return {
      indexForm: {
        channelName: '',
        channelCode: '',
        channelAddress: '',
        zipCode: '',
        personInCharge: '',
        idNo: '',
        bankName: '',
        bankNo: '',
        phone: '',
        createTime: ''
      },
      addComponent: false,
      updateComponent: false,
      updateId: '',
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: []
    }
  },

  mounted () {
    var userSubscriptionStockOut2ToChannel = sessionStorage.getItem('userSubscriptionStockOut2ToChannel')
    if (userSubscriptionStockOut2ToChannel != undefined) {
      this.indexForm.channelCode = userSubscriptionStockOut2ToChannel
    }
    this.fetchData()
  },
  beforeDestroy () {
    sessionStorage.removeItem('userSubscriptionStockOut2ToChannel')
  },
  methods: {
    fetchData () {
      this.loading = true
      findAllListByPage({
        channelName: this.indexForm.channelName,
        channelCode: this.indexForm.channelCode,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        console.log(res)
        this.tableData = res.data.content
        this.total = res.data.total
        this.loading = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.fetchData()
    },
    filterStatus (value, row) {
      return row.status === value
    },
    deleteRow (index, row) {
      this.$confirm('确认删除' + row.channelName + '？').then(_ => {
        this.loading = true
        del({
          channelInfoId: row.id
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    deleteBatchRows () {
      this.$confirm('确认需要批量删除吗？').then(_ => {
        this.loading = true
        let idsStr = ''
        this.multipleSelection.forEach(row => {
          idsStr = idsStr + ',' + row.id
        })
        // 截取第1个之后所有的字符
        idsStr = idsStr.slice(1)
        deleteBatchChannelInfo({
          channelInfoIdsStr: idsStr
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    forCooperationPriceRate (row, column) {
      return row.cooperationPriceRate * 100 + '%'
    },
    forDateCreate (row, column) {
      return row.createTime == null ? '' : dayjs(row.createTime).format('YYYY-MM-DD')
    },
    forDateRevise (row, column) {
      return row.reviseTime == null ? '' : dayjs(row.reviseTime).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    submitForm (formName) {
      this.fetchData()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.indexForm.brandIds = []
      this.indexForm.categoryIds = []
      this.fetchData()
    },
    add () {
      this.addComponent = !this.addComponent
    },
    onAddPageChange (val) {
      this.addComponent = val// ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    update () {
      this.updateComponent = !this.updateComponent
    },
    onUpdatePageChange (val) {
      this.updateComponent = val// ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    updateRow (id) {
      this.update()
      this.idChange(id)
    },
    idChange (val) {
      this.updateId = val
    },
    onIdChange (val) {
      this.updateId = val// ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    restartCooperation (index, row) {
      this.$confirm('是否确定要与【' + row.channelName + '】渠道重新合作？').then(_ => {
        this.loading = true
        restartCooperation({
          channelInfoId: row.id
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },
    suspendCooperation (index, row) {
      this.$confirm('是否确定要与【' + row.channelName + '】渠道暂停合作？').then(_ => {
        this.loading = true
        suspendCooperation({
          channelInfoId: row.id
        })
          .then(res => {
            var code = res.code
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    }
  }
}
</script>
